<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="85%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-divider content-position="left">
        <span class="divider-text">概要信息</span>
      </el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同类型" prop="contractType">
            <el-select
              v-model="formData.contractType"
              class="w-1/1"
              placeholder="请选择合同类型"
              @blur="generateContractName"
              :disabled="renewFlag"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_ARCHIVE_CONTRACT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否试用" prop="isTest">
            <el-select
              v-model="formData.isTest"
              class="w-1/1"
              placeholder="请选择是否试用"
              :disabled="renewFlag"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_ARCHIVE_IS_TEST)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="委托单位(甲方)" prop="customerName">
            <el-select
              v-model="formData.customerName"
              class="w-1/1"
              placeholder="请选择委托单位(甲方)"
              @change="handleSelectedCustomer"
              :disabled="renewFlag"
            >
              <el-option
                v-for="dict in customerList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签约时间" prop="signTime">
            <el-date-picker
              v-model="formData.signTime"
              type="date"
              value-format="x"
              placeholder="选择签约时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="formData.contractName" placeholder="请输入合同名称" />
          </el-form-item>
        </el-col>
        <el-col :span="11" v-show="formData.isTest !== '1'">
          <el-form-item label="合同编号" prop="contractCode">
            <el-input v-model="formData.contractCode" placeholder="请输入合同编号" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button plain type="primary" @click="generateContractCode">生成</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="用电户号" prop="powerAccount">
            <el-input v-model="formData.powerAccount" placeholder="请输入用电户号" />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button plain type="primary" @click="openPowerAccountDialog">选择</el-button>
        </el-col>
        <el-col :span="11">
          <el-form-item label="项目编码" prop="projectCode">
            <el-input v-model="formData.projectCode" placeholder="请输入项目编码" />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button plain type="primary" @click="generateProjectCode">生成</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="甲方代表" prop="customerDirectorName">
            <el-input v-model="formData.customerDirectorName" placeholder="请输入甲方代表" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactNumber">
            <el-input v-model="formData.contactNumber" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="乙方代表(签约人)" prop="companyDirectorName">
            <el-select
              v-model="formData.companyDirectorName"
              :disabled="formType !== 'create'"
              class="w-1/1"
              placeholder="请选择乙方代表(签约人)"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="11">
          <el-form-item label="管理单元" prop="manageUnitName">
            <el-input v-model="formData.manageUnitName" placeholder="请选择管理单元" />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button plain type="primary" @click="openServiceUnitDialog()">选择</el-button>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="管理单元" prop="manageUnitId">
            <el-select
              v-model="formData.manageUnitId"
              class="w-1/1"
              placeholder="请选择管理单元"
              @change="syncServiceUint"
            >
              <el-option
                v-for="dict in serviceUnitList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户经理" prop="costomerManager">
            <el-input v-model="formData.costomerManager" placeholder="请输入客户经理" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用电位置" prop="powerLocation">
            <el-cascader
              v-model="formData.powerLocation"
              :options="areaList"
              :props="defaultProps"
              class="w-1/1"
              clearable
              filterable
              placeholder="请选择电位置省市区"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用电地址" prop="powerAddress">
            <el-input v-model="formData.powerAddress" placeholder="请输入用电地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用电片区" prop="powerArea">
            <el-input v-model="formData.powerArea" placeholder="请输入用电片区" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">
        <span class="divider-text">项目内容</span>
      </el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同服务项目" prop="serviceContent">
            <el-select
              v-model="formData.serviceContent"
              multiple
              placeholder="请选择合同服务项目"
              :disabled="renewFlag"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_ARCHIVE_SERVICE_CONTENT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="补充条款" prop="supplement">
            <el-input v-model="formData.supplement" placeholder="请输入补充条款" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">
        <span class="divider-text">变压器容量及数量</span>
      </el-divider>
      <!-- 变压器 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="变压器明细">
            <el-button type="primary" plain @click="handleAddTransformer">添加变压器</el-button>
            <el-table
              :data="formData.transformerList"
              :show-overflow-tooltip="true"
              :stripe="true"
              height="200"
            >
              <el-table-column label="容量(kVA)" prop="volume" align="center">
                <template #default="{ row }">
                  <el-input
                    v-model="row.volume"
                    placeholder="请输入容量"
                    @blur="calculateTransformerInfo"
                  />
                </template>
              </el-table-column>
              <el-table-column label="数量(台)" prop="amount" align="center">
                <template #default="{ row }">
                  <el-input
                    v-model="row.amount"
                    placeholder="请输入数量"
                    @blur="calculateTransformerInfo"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" fixed="right" label="操作" width="130">
                <template #default="{ $index }">
                  <el-button link type="danger" @click="handleDeleteTransformer($index)">
                    移除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="变压器总容量(kVA)" prop="totalVolume">
            <el-input v-model="formData.totalVolume" placeholder="请输入变压器总容量" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="变压器总数量" prop="transformerAmount">
            <el-input v-model="formData.transformerAmount" placeholder="请输入变压器总数量" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="应安装监测表数量" prop="measureAmount">
            <el-input v-model="formData.measureAmount" placeholder="请输入应安装监测表数量" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">
        <span class="divider-text">合同期限</span>
      </el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同开始时间" prop="contractStartTime">
            <el-date-picker
              v-model="formData.contractStartTime"
              type="date"
              value-format="x"
              placeholder="选择合同开始时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同终止时间" prop="contractEndTime">
            <el-date-picker
              v-model="formData.contractEndTime"
              type="date"
              value-format="x"
              placeholder="选择合同终止时间"
              style="width: 100%"
              @blur="calculateContractMonth"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="合同服务期限" prop="contractMonthNumber">
            <el-input
              v-model="formData.contractMonthNumber"
              placeholder="请输入合同服务期限"
              @blur="convertContractMonthNumberToText"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1"><span>月</span></el-col>
        <el-col :span="10">
          <el-form-item label="" prop="contractMonthText">
            <el-input
              v-model="formData.contractMonthText"
              placeholder="请输入合同服务期限大写"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="2"><span>月(大写)</span></el-col>
      </el-row>
      <el-divider content-position="left">
        <span class="divider-text">合同价款、支付及结算方式</span>
      </el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="月服务费" prop="feePerMontNumber">
            <el-input
              v-model="formData.feePerMontNumber"
              placeholder="请输入月服务费"
              @blur="convertFeePerMontNumberToText"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="月服务费大写" prop="feePerMontText">
            <el-input v-model="formData.feePerMontText" placeholder="请输入月服务费大写" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="实际月服务费" prop="factFeePerMonthNumber">
            <el-input
              v-model="formData.factFeePerMonthNumber"
              placeholder="请输入实际月服务费"
              @blur="convertFactFeePerMonthNumberToText"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实际月服务费大写" prop="factFeePerMonthText">
            <el-input
              v-model="formData.factFeePerMonthText"
              placeholder="请输入实际月服务费大写"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同总价" prop="contractPriceNumber">
            <el-input
              v-model="formData.contractPriceNumber"
              placeholder="请输入合同总价"
              @blur="convertContractPriceNumberToText"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同总价大写" prop="contractPriceText">
            <el-input
              v-model="formData.contractPriceText"
              placeholder="请输入合同总价大写"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="首次付款金额" prop="firstPay">
            <el-input v-model="formData.firstPay" placeholder="请输入首次付款金额" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="首次支付时间" prop="firstPayDate">
            <el-date-picker
              v-model="formData.firstPayDate"
              type="date"
              value-format="x"
              placeholder="选择首次支付时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="分期期数" prop="instalmentCount">
            <el-input
              v-model="formData.instalmentCount"
              placeholder="请输入分期期数"
              @blur="calculateIntervalPay"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分期收款间隔(月)" prop="receiveInterval">
            <el-input v-model="formData.receiveInterval" placeholder="请输入分期收款间隔(月)" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="每期支付金额" prop="intervalPay">
            <el-input v-model="formData.intervalPay" placeholder="请输入每期支付金额" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- 应收款记录 -->
        <el-col :span="24">
          <el-form-item label="分期明细">
            <el-button type="primary" plain @click="generateInstalmentInfo">生成</el-button>
            <el-button type="success" plain @click="createInstalmentInfo">新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table
        :data="formData.receiveRecordList"
        :show-overflow-tooltip="true"
        :stripe="true"
        height="200"
      >
        <el-table-column label="期数" prop="instalmentCount" align="center" width="70">
          <template #default="{ row }">
            <el-input v-model="row.instalmentCount" placeholder="请输入期数" />
          </template>
        </el-table-column>
        <el-table-column label="收款状态" prop="status" align="center" width="120">
          <template #default="{ row }">
            <el-select v-model="row.status" placeholder="请选择收款状态">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_ARCHIVE_RECEIVE_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="收款日期" prop="receiveDate" align="center" width="120">
          <template #default="{ row }">
            <el-input v-model="row.receiveDate" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="收款金额(元)" prop="receiveMoney" align="center">
          <template #default="{ row }">
            <el-input v-model="row.receiveMoney" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="发票号码" prop="receiptCode" align="center">
          <template #default="{ row }">
            <el-input v-model="row.receiptCode" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="已收金额(元)" prop="alreadyReceiveMoney" align="center">
          <template #default="{ row }">
            <el-input v-model="row.alreadyReceiveMoney" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="对应服务期" prop="serviceTerm" align="center" width="210">
          <template #default="{ row }">
            <el-input v-model="row.serviceTerm" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center">
          <template #default="{ row }">
            <el-input v-model="row.remark" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="坏账原因" prop="badDebtReason" align="center">
          <template #default="{ row }">
            <el-input v-model="row.badDebtReason" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="130">
          <template #default="{ $index }">
            <el-button link type="danger" @click="handleDeleteInstalment($index)"> 移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-divider content-position="left">
        <span class="divider-text">合同执行及其他</span>
      </el-divider>
      <el-row>
        <!-- <el-col :span="11">
          <el-form-item label="服务单元" prop="serviceUnitName">
            <el-input v-model="formData.serviceUnitName" placeholder="请输入服务单元" />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button plain type="primary" @click="openServiceUnitDialog()">选择</el-button>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="服务单元" prop="serviceUnitId">
            <el-select v-model="formData.serviceUnitId" class="w-1/1" placeholder="请选择服务单元">
              <el-option
                v-for="dict in serviceUnitList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务经理" prop="serviceManagerName">
            <el-input v-model="formData.serviceManagerName" placeholder="请输入服务经理" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="介绍人" prop="introducer">
            <el-input v-model="formData.introducer" placeholder="请输入介绍人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="介绍渠道" prop="introduceChannel">
            <el-input v-model="formData.introduceChannel" placeholder="请输入介绍渠道" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="附件" prop="attachmentUrl">
            <UploadFile v-model="formData.attachmentUrl" class="min-w-80px" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        v-if="renewFlag == false"
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        >确 定</el-button
      >
      <el-button
        v-if="renewFlag == true"
        @click="submitRenew"
        type="primary"
        :disabled="formLoading"
        >续 签</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <PowerAccountDialog ref="powerAccountDialogRef" @success="handleSelectedPowerAccount" />
  <ServiceUnitDialog ref="serviceunitDialogRef" @success="handleSelectedServiceUnit" />
</template>

<script setup lang="ts">
import { ContractArchiveApi, ContractArchive } from '@/api/biz/contract'
import { formatDate } from '@/utils/formatTime'
import * as UserApi from '@/api/system/user'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { numToCny, numberToChinese } from '@/utils'
import { useUserStore } from '@/store/modules/user'
import { defaultProps } from '@/utils/tree'
import * as AreaApi from '@/api/system/area'
import PowerAccountDialog from './PowerAccountDialog.vue'
import ServiceUnitDialog from './ServiceUnitDialog.vue'
import { differenceInMonths } from 'date-fns'
import { CustomerArchiveApi } from '@/api/biz/customer'
import { CustomerArchiveServiceUnitApi } from '@/api/biz/customer/serviceunit'

/** 合同档案 表单 */
defineOptions({ name: 'ContractArchiveForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  contractType: undefined,
  isTest: undefined,
  contractName: undefined,
  contractCode: undefined,
  customerId: undefined,
  customerName: undefined,
  signTime: undefined,
  powerAccountId: undefined,
  powerAccount: undefined,
  projectCode: undefined,
  customerDirectorName: undefined,
  contactNumber: undefined,
  companyDirectorName: undefined,
  manageUnitId: undefined,
  manageUnitName: undefined,
  costomerManager: undefined,
  powerLocation: undefined,
  powerAddress: undefined,
  powerArea: undefined,
  serviceContent: undefined,
  supplement: undefined,
  transformerAmount: undefined,
  totalVolume: undefined,
  measureAmount: undefined,
  contractStartTime: undefined,
  contractEndTime: undefined,
  contractMonthNumber: undefined,
  contractMonthText: undefined,
  feePerMontNumber: undefined,
  feePerMontText: undefined,
  factFeePerMonthNumber: undefined,
  factFeePerMonthText: undefined,
  contractPriceNumber: undefined,
  contractPriceText: undefined,
  firstPay: undefined,
  firstPayDate: undefined,
  instalmentCount: undefined,
  receiveInterval: undefined,
  intervalPay: undefined,
  serviceUnitId: undefined,
  serviceUnitName: undefined,
  serviceManagerName: undefined,
  introducer: undefined,
  introduceChannel: undefined,
  remark: undefined,
  attachmentUrl: undefined,
  ownerUserId: undefined,
  transformerList: [],
  receiveRecordList: [],
  status: undefined
})
const formRules = reactive({
  contractType: [{ required: true, message: '合同类型不能为空', trigger: 'blur' }],
  customerName: [{ required: true, message: '委托单位(甲方)不能为空', trigger: 'blur' }],
  signTime: [{ required: true, message: '签约时间不能为空', trigger: 'blur' }],
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  powerAccount: [{ required: true, message: '用电户号不能为空', trigger: 'blur' }],
  manageUnitName: [{ required: true, message: '管理单元不能为空', trigger: 'blur' }],
  contractStartTime: [{ required: true, message: '合同开始时间不能为空', trigger: 'blur' }],
  contractEndTime: [{ required: true, message: '合同终止时间不能为空', trigger: 'blur' }],
  feePerMontNumber: [{ required: true, message: '月服务费不能为空', trigger: 'blur' }],
  factFeePerMonthNumber: [{ required: true, message: '实际月服务费不能为空', trigger: 'blur' }],
  serviceUnitName: [{ required: true, message: '服务单元不能为空', trigger: 'blur' }],
  serviceManagerName: [{ required: true, message: '服务经理不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const areaList = ref([]) // 地区列表
const renewFlag = ref(false)
const customerList = ref([]) // 委托单位甲方列表
const serviceUnitList = ref([]) // 服务单元列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
  // 根据登录人获取客户列表
  formData.value.ownerUserId = useUserStore().getUser.id
  customerList.value = await CustomerArchiveApi.getSimpleList({
    ownerUserId: formData.value.ownerUserId
  })

  // 获取服务单元列表
  serviceUnitList.value = await CustomerArchiveServiceUnitApi.getSimpleList()

  if (formType.value === 'create') {
    // 初始化字段值
    formData.value.serviceContent = ['1', '2', '3', '4'] // 合同服务内容
    formData.value.ownerUserId = useUserStore().getUser.id // 合同负责人id
    formData.value.companyDirectorName = useUserStore().getUser.nickname // 乙方代表(签约人)
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ContractArchiveApi.getContractArchive(id)
      // 格式化收款日期
      if (formData.value.receiveRecordList) {
        formData.value.receiveRecordList.forEach((item) => {
          item.receiveDate = formatDate(item.receiveDate)
        })
      }
      if (type === 'renew') {
        renewFlag.value = true
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 收款日期转型
    if (formData.value.receiveRecordList) {
      formData.value.receiveRecordList.forEach((item) => {
        item.receiveDate = Date.parse(item.receiveDate)
      })
    }
    const data = {
      ...formData.value
    } as unknown as ContractArchive

    if (formType.value === 'create' && formData.value.id == undefined) {
      await ContractArchiveApi.createContractArchive(data)
      message.success(t('common.createSuccess'))
    } else {
      await ContractArchiveApi.updateContractArchive(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    contractType: undefined,
    isTest: undefined,
    contractName: undefined,
    contractCode: undefined,
    customerId: undefined,
    customerName: undefined,
    signTime: undefined,
    powerAccountId: undefined,
    powerAccount: undefined,
    projectCode: undefined,
    customerDirectorName: undefined,
    contactNumber: undefined,
    companyDirectorName: undefined,
    manageUnitId: undefined,
    manageUnitName: undefined,
    costomerManager: undefined,
    powerLocation: undefined,
    powerAddress: undefined,
    powerArea: undefined,
    serviceContent: undefined,
    supplement: undefined,
    transformerAmount: undefined,
    totalVolume: undefined,
    measureAmount: undefined,
    contractStartTime: undefined,
    contractEndTime: undefined,
    contractMonthNumber: undefined,
    contractMonthText: undefined,
    // 分期
    feePerMontNumber: undefined,
    feePerMontText: undefined,
    factFeePerMonthNumber: undefined,
    factFeePerMonthText: undefined,
    contractPriceNumber: undefined,
    contractPriceText: undefined,
    firstPay: undefined,
    firstPayDate: undefined,
    instalmentCount: undefined,
    receiveInterval: undefined,
    intervalPay: undefined,
    serviceUnitId: undefined,
    serviceUnitName: undefined,
    serviceManagerName: undefined,
    introducer: undefined,
    introduceChannel: undefined,
    remark: undefined,
    attachmentUrl: undefined,
    ownerUserId: undefined,
    transformerList: [],
    receiveRecordList: [],
    status: undefined
  }
  formRef.value?.resetFields()
}

const handleAddTransformer = () => {
  formData.value.transformerList.push({ volume: 0, amount: 0 })
  calculateTransformerInfo()
}

const handleDeleteTransformer = (index) => {
  formData.value.transformerList.splice(index, 1)
  calculateTransformerInfo()
}

const calculateTransformerInfo = () => {
  var transformerTotalVolume = 0
  var transformerTotalAmount = 0
  if (formData.value.transformerList.length > 0) {
    formData.value.transformerList.forEach((item) => {
      transformerTotalVolume += parseInt(item.volume)
      transformerTotalAmount += parseInt(item.amount)
    })
  } else {
    transformerTotalVolume = 0
    transformerTotalAmount = 0
  }
  formData.value.transformerAmount = transformerTotalAmount
  formData.value.totalVolume = transformerTotalVolume
  formData.value.measureAmount = transformerTotalAmount
}

const createInstalmentInfo = () => {
  formData.value.receiveRecordList.push({
    instalmentCount: formData.value.receiveRecordList.length + 1,
    status: '0',
    receiveDate: getCurrentDate(),
    receiveMoney: 0.0,
    receiptCode: '',
    alreadyPayment: 0.0,
    serviceTerm: getCurrentDate() + '至' + getReceiveDate(new Date(), 1),
    remark: '',
    badReason: ''
  })
}

const handleDeleteInstalment = (index) => {
  formData.value.receiveRecordList.splice(index, 1)
}

const generateInstalmentInfo = () => {
  formData.value.receiveRecordList = []
  const validResult = validInstalmentCondition()
  if (validResult) {
    const instalmentInfo = getInstalmentInfo()
    console.log(instalmentInfo)
    // 按分期数,生成分期记录
    if (instalmentInfo.value.instalmentCount > 0) {
      // 首付记录
      formData.value.receiveRecordList.push({
        instalmentCount: 1,
        status: '0',
        receiveDate: getCurrentDate(instalmentInfo.value.firstPayDate),
        receiveMoney: instalmentInfo.value.firstPay,
        receiptCode: '',
        alreadyPayment: instalmentInfo.value.firstPay,
        serviceTerm:
          getCurrentDate(formData.value.contractStartTime) +
          '至' +
          getReceiveDate(
            formData.value.contractStartTime,
            instalmentInfo.value.receiveInterval * 1
          ),
        remark: '',
        badReason: ''
      })
      // 计算分期
      for (var i = 1; i <= instalmentInfo.value.instalmentCount; i++) {
        if (i != instalmentInfo.value.instalmentCount) {
          formData.value.receiveRecordList.push({
            instalmentCount: i + 1,
            status: '0',
            receiveDate: getReceiveDate(
              instalmentInfo.value.firstPayDate,
              instalmentInfo.value.receiveInterval * i
            ),
            receiveMoney: instalmentInfo.value.intervalPay,
            receiptCode: '',
            alreadyPayment: 0.0,
            serviceTerm:
              getReceiveDate(
                formData.value.contractStartTime,
                instalmentInfo.value.receiveInterval * i
              ) +
              '至' +
              getReceiveDate(
                formData.value.contractStartTime,
                instalmentInfo.value.receiveInterval * (i + 1)
              ),
            remark: '',
            badReason: ''
          })
        } else {
          formData.value.receiveRecordList.push({
            instalmentCount: i + 1,
            status: '0',
            receiveDate: getReceiveDate(
              instalmentInfo.value.firstPayDate,
              instalmentInfo.value.receiveInterval * i
            ),
            receiveMoney: instalmentInfo.value.intervalPay,
            receiptCode: '',
            alreadyPayment: 0.0,
            serviceTerm:
              getReceiveDate(
                formData.value.contractStartTime,
                instalmentInfo.value.receiveInterval * i
              ) +
              '至' +
              getCurrentDate(formData.value.contractEndTime),
            remark: '',
            badReason: ''
          })
        }
      }
    } else {
      // 不分期
      formData.value.receiveRecordList.push({
        instalmentCount: 1,
        status: '0',
        receiveDate: getCurrentDate(instalmentInfo.value.firstPayDate),
        receiveMoney: instalmentInfo.value.firstPay,
        receiptCode: '',
        alreadyPayment: instalmentInfo.value.firstPay,
        serviceTerm:
          getCurrentDate(formData.value.contractStartTime) +
          '至' +
          getCurrentDate(formData.value.contractEndTime),
        remark: '',
        badReason: ''
      })
    }
  }
  console.log(formData.value.receiveRecordList)
}

const validInstalmentCondition = () => {
  if (
    formData.value.contractStartTime !== undefined &&
    formData.value.contractEndTime !== undefined
  ) {
    // 合同金额
    if (
      formData.value.contractPriceNumber !== undefined &&
      formData.value.contractPriceNumber > 0
    ) {
      // 首付金额
      if (formData.value.firstPay !== undefined && formData.value.firstPay >= 0) {
        // 首付日期
        if (formData.value.firstPayDate !== undefined) {
          // 分期数
          if (formData.value.instalmentCount !== undefined && formData.value.instalmentCount >= 0) {
            // 收款间隔
            if (
              formData.value.receiveInterval !== undefined &&
              formData.value.receiveInterval >= 0
            ) {
              // 每期费用
              if (formData.value.intervalPay !== undefined && formData.value.intervalPay >= 0) {
                return true
              } else {
                ElMessage.warning('每期支付金额不正确')
                return false
              }
            } else {
              ElMessage.warning('分期收款间隔不正确')
              return false
            }
          } else {
            ElMessage.warning('分期期数不正确')
            return false
          }
        } else {
          ElMessage.warning('首次支付时间不正确')
          return false
        }
      } else {
        ElMessage.warning('首次付款金额不正确')
        return false
      }
    } else {
      ElMessage.warning('合同总价不正确')
      return false
    }
  } else {
    ElMessage.warning('合同起止时间不正确')
    return false
  }
}

const getInstalmentInfo = () => {
  const instalmentInfo = ref({})
  instalmentInfo.value.contractPriceNumber = formData.value.contractPriceNumber
  instalmentInfo.value.firstPay = formData.value.firstPay
  instalmentInfo.value.firstPayDate = formData.value.firstPayDate
  instalmentInfo.value.instalmentCount = formData.value.instalmentCount
  instalmentInfo.value.receiveInterval = formData.value.receiveInterval
  instalmentInfo.value.intervalPay = formData.value.intervalPay
  return instalmentInfo
}

const getCurrentDate = (date?: Date) => {
  const currentDate = ref()
  if (date) {
    currentDate.value = formatDate(date, 'YYYY-MM-DD')
  } else {
    currentDate.value = formatDate(new Date(), 'YYYY-MM-DD')
  }
  return currentDate.value
}

const getReceiveDate = (date: Date, months: number): Date => {
  const result = new Date(date)
  result.setMonth(result.getMonth() + months)
  return formatDate(result, 'YYYY-MM-DD')
}

const calculateIntervalPay = () => {
  if (
    formData.value.contractPriceNumber > 0 &&
    formData.value.firstPay >= 0 &&
    formData.value.instalmentCount > 0
  ) {
    formData.value.intervalPay =
      (formData.value.contractPriceNumber - formData.value.firstPay) /
      formData.value.instalmentCount
  }

  if (formData.value.instalmentCount == 0) {
    formData.value.intervalPay = 0
  }
}

// 数字金额转汉字大写
const convertContractMonthNumberToText = () => {
  if (formData.value.contractMonthNumber) {
    formData.value.contractMonthText = numberToChinese(String(formData.value.contractMonthNumber))
  }
}

const convertFeePerMontNumberToText = () => {
  formData.value.feePerMontText = undefined
  if (formData.value.feePerMontNumber) {
    formData.value.feePerMontText = numToCny(String(formData.value.feePerMontNumber))
  }
}

const convertFactFeePerMonthNumberToText = () => {
  if (formData.value.factFeePerMonthNumber) {
    formData.value.factFeePerMonthText = numToCny(String(formData.value.factFeePerMonthNumber))
    calculateContractPrice()
  }
}

const convertContractPriceNumberToText = () => {
  formData.value.contractPriceText = undefined
  if (formData.value.contractPriceNumber) {
    formData.value.contractPriceText = numToCny(String(formData.value.contractPriceNumber))
  }
}

const expandTargetCustomerId = ref()
const handleSelectedCustomer = async (customerId) => {
  if (customerId != undefined) {
    const customerData = await CustomerArchiveApi.getCustomerArchive(customerId)
    formData.value.customerId = customerData.id
    formData.value.customerName = customerData.name
    formData.value.customerDirectorName = customerData.contactName
    formData.value.contactNumber = customerData.contactNumber
    formData.value.powerAddress = customerData.address
    expandTargetCustomerId.value = customerData.expandTargetCustomerId
  }
  generateContractName()
}

/** 打开用电户号列表 */
const powerAccountDialogRef = ref()
const openPowerAccountDialog = () => {
  // powerAccountDialogRef.value.open(formData.value.customerId)
  powerAccountDialogRef.value.open(expandTargetCustomerId.value)
}

const handleSelectedPowerAccount = (powerAccountData) => {
  if (powerAccountData !== undefined) {
    formData.value.powerAccountId = powerAccountData.map((item) => item.id).join(',')
    formData.value.powerAccount = powerAccountData.map((item) => item.account).join(',')
  }
  generateContractName()
}

const generateContractName = () => {
  if (formData.value.contractType != undefined && formData.value.customerName != undefined) {
    const label = getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_ARCHIVE_CONTRACT_TYPE)
      .filter((dict) => dict.value == formData.value.contractType)
      .map((dict) => dict.label)
    formData.value.contractName = formData.value.customerName + label + '合同'
  }
}

/** 打开拓展客户列表 */
const serviceunitDialogRef = ref()
const openServiceUnitDialog = () => {
  serviceunitDialogRef.value.open()
}

const handleSelectedServiceUnit = (serviceUnitData) => {
  if (serviceUnitData !== undefined) {
    formData.value.serviceUnitId = serviceUnitData.id
    formData.value.serviceUnitName = serviceUnitData.name
    formData.value.manageUnitId = serviceUnitData.id
    formData.value.manageUnitName = serviceUnitData.name
  }
}

const calculateContractPrice = () => {
  if (
    formData.value.contractMonthNumber != undefined &&
    formData.value.factFeePerMonthNumber != undefined
  ) {
    formData.value.contractPriceNumber =
      formData.value.factFeePerMonthNumber * formData.value.contractMonthNumber
    convertContractPriceNumberToText()
  }
}

const calculateContractMonth = () => {
  if (
    formData.value.contractStartTime != undefined &&
    formData.value.contractEndTime != undefined
  ) {
    formData.value.contractMonthNumber =
      differenceInMonths(formData.value.contractEndTime, formData.value.contractStartTime) + 1
  }
  convertContractMonthNumberToText()
}

const submitRenew = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 收款日期转型并清空原始合同id
    if (formData.value.receiveRecordList) {
      formData.value.receiveRecordList.forEach((item) => {
        item.id = undefined
        item.contractArchiveId = undefined
        item.receiveDate = Date.parse(item.receiveDate)
      })
    }
    if (formData.value.transformerList) {
      formData.value.transformerList.forEach((item) => {
        item.id = undefined
        item.contractArchiveId = undefined
      })
    }
    const data = {
      ...formData.value
    } as unknown as ContractArchive
    console.log(data)
    if (formData.value.id != undefined && formData.value.status == '3') {
      await ContractArchiveApi.renewContractArchive(data)
      message.success(t('续签成功'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const syncServiceUint = async (value) => {
  formData.value.serviceUnitId = formData.value.manageUnitId
  const selectedItem = serviceUnitList.value.find((item) => item.value === value)
  formData.value.manageUnitName = selectedItem.label
  formData.value.serviceUnitName = formData.value.manageUnitName
}

const generateContractCode = async () => {
  formData.value.contractCode = await ContractArchiveApi.getAutoGenerateCode('contract001')
}

const generateProjectCode = async () => {
  formData.value.projectCode = await ContractArchiveApi.getAutoGenerateCode('project001')
}
</script>
<style scoped>
.divider-text {
  color: #50a6ff;
}
</style>
